<?php
namespace core\helper;
use \think\exception\ClassNotFoundException;
use think\Container;
class Log{
    
    
    protected static $log = []; //日志信息
    protected static $config = [
        
    ]; //配置参数
    protected static $type = ['log','debug', 'info', 'sql', 'notice', 'error', 'exception']; // 日志类型
    protected static $driver; // 日志写入驱动 log\driver\File|log\driver\Test|log\driver\Socket 
    protected static $key; // 当前日志授权 key
    
    private static $exceptionHandle;   //异常日志记录处理
    private static $writeType = 1 ;    //日志写入方式 1 按顺序写入 2 、按分组写入
    
    
    
    /**
     * 获取日志信息
     */
    public static function getLog($level = ''){
        return $level ? self::$log[$level] : self::$log;
    }

    /**
     * 清空日志信息
     */
    public static function clear(){
        self::$log = [];
    }
    
    /**
     * 记录日志信息
     * @param  mixed  $message  调试信息
     * @param  string $level 日志级别
     */
    public static function add($message, $level = 'log'){
        $emask = $level;
        if( $message instanceof \Exception ) $level = 'exception';
        $message = self::check($message,$emask);
        if( self::$writeType == 1){
            self::$log[] = [
                'level' => $level,
                'emask' => $emask,
                'data'  => $message
            ];
        }else{
            self::$log[$level][] = $message;
        }        
        PHP_SAPI == 'cli' && self::save();
    }
    
    /**
     * 实时写入日志信息 并支持行为
     * @access public
     * @param  mixed  $message   调试信息
     * @param  string $level  信息类型
     * @param  bool   $force 是否强制写入
     */
    public static function write($message, $level = 'log', $force = false){
        $emask = $level;
        if( $message instanceof \Exception ) $level = 'exception';
        $message = self::check($message,$emask);        
        $log = self::$log;
        // 如果不是强制写入，而且信息类型不在可记录的类别中则直接返回 false 不做记录
        if (true !== $force && !empty(self::$config['level']) && !in_array($level, self::$config['level'])) {
            return false;
        }
        // 封装日志信息
        if( self::$writeType == 1){
            self::$log[] = [
                'level' => $level,
                'emask' => $emask,
                'data'  => $message
            ];
        }else{
            self::$log[$level][] = $message;
        }
        is_null(self::$driver) && self::init();
        // 写入日志
        if ($result = self::$driver->save($log)) {
            self::$log = [];
        }
        return $result;
    }

    /**
     * 保存调试信息
     * @access public
     * @return bool
     */
    public static function save(){
        // 没有需要保存的记录则直接返回
        if (empty(self::$log)) {
            return true;
        }        
        is_null(self::$driver) && self::init();
        $log = self::$log;
        if (empty(self::$config['level'])) {
            // 获取全部日志
            /*
            $log = self::$log;
            if (!App::$debug && isset($log['debug'])) {
                unset($log['debug']);
            }*/
        } else {
            // 记录允许级别
            $log = [];
            if( self::$writeType == 1){
                foreach( self::$log as $val ){
                    if( in_array( $val['level'],self::$config['level'])){
                        $log[] = $val;
                    }
                }
            }else{
                foreach (self::$config['level'] as $level) {
                    if (isset(self::$log[$level])) {
                        $log[$level] = self::$log[$level];
                    }
                }
            }
        }        
        if ($result = self::$driver->save($log)) {
            self::$log = [];
        }
        return $result;
    }
    
    /**
     * 日志初始化
     * @access public
     * @param  array $config 配置参数
     * @return void
     */
    private static function init($config = []){  
        $class = '\\core\\log\\File';        
        if (class_exists($class)) {            
            $app = app();
            $modelpath = $app->getModulePath();
            $model = basename($modelpath);
           // $model = $model ? $model : 'cli';            
            $logpath = $app->getRuntimePath().'logcore'.DIRECTORY_SEPARATOR.$model.DIRECTORY_SEPARATOR;            
            $config = [
                'time_format' => ' Y-m-d H:i:s ',
              //  'single'      => false,
              // 'file_size'   => 2097152,
                'path'        => $logpath,
              //  'apart_level' => [],
            ];
            self::$driver = new $class($config);
        } else {
            throw new ClassNotFoundException('class not exists:' . $class, $class);
        }
    }
    
    /**
     * 检查过滤写入的日志信息
     */
    private static function check($message,$level){
        if( $message instanceof \Exception ){
            $ExceptionHandle = \core\log\ExceptionHandle::instance();
            return $ExceptionHandle->report($message,$level);
        }
       // if( is_object( $message ) ) $message = var_export( serialize( $message) ,true);
        return $message;
    }
    
}
